/**
 * Created by chengxm on 2018-04-09.
 */
import {Component, ViewChild} from '@angular/core';
import {GridConfigService} from '@core/config/grid-config.service';

import {
  extend, getO, missing, type, fillField, replaceAll, deepClone, missingOrEmpty, agCurrency, agNumber,
} from '../../../../utils/utils';

import {Events} from '@core/services/events/Events';
import {ExpressionService} from '@core/services/expression/ExpressionService';
import {ApiService} from '@core/services/http/api.service';
import {ApesField} from '@shared/ui-zorro/src/types/apes-field';
import {SubjectService} from '@core/services/events/subject.service';
import {RenderOperatingButtonComponent} from '@shared/ag-grid-ext/cell-renders/render-operating-button.component';
import {EditorDateComponent} from '@shared/ag-grid-ext/cell-editors/editor-date.component';
import {GridOptions} from '@ag-grid-community/core';
import {ApesMessageService} from '@shared/apes/message';
import {toBoolean} from '@shared/apes/core';
import {XlsxService} from '@shared/apes/xlsx';
import {ApesRenderLinkComponent} from "@shared/ag-grid-ext/cell-renders/render-link.component";
import {DrillThroughService} from "@shared/ui-zorro/src/services/drill-through.service";
import {AllModules, Module} from "@ag-grid-enterprise/all-modules";
import {format} from "date-fns";
import { RenderUploadComponent } from '@shared/ag-grid-ext/cell-renders/render-upload.component';
import { RenderTooltipComponent } from '@shared/ag-grid-ext/cell-renders/render-tooltip.component';
import { ApesLoadingOverlayComponent } from '@shared/ag-grid-ext/loading-overlay/apes-loading-overlay.component';
import { ApesNoRowsOverlayComponent } from '@shared/ag-grid-ext/noRows-overlay/apes-noRows-overlay.component';


function operationCellRenderer(params) {
  if (params.value == 'sum')
    return '合计:'
  else
    return params.rowIndex + 1;
}

@Component({
  selector: 'formly-field-grid-display',
  template: `
    <div apes-row [apesGutter]="8">
      <apes-breadcrumb>
        <apes-breadcrumb-item *ngFor="let breadcrumb  of breadcrumbArray;let i =index">
          <a *ngIf="i < breadcrumbArray.length-1 else temp" (click)="jump(i,breadcrumb)">{{breadcrumb.name}}</a>
          <ng-template #temp>{{breadcrumb.name}}</ng-template>
        </apes-breadcrumb-item>
      </apes-breadcrumb>
      <div *ngIf="btnRemarks != ''" style="position:absolute;color: red;padding: 3px 10px;">{{btnRemarks}}</div>
      <div *ngIf="getExport()" style="display:flex;flex-direction: row-reverse">
<!--        <button *ngIf="!getButtonHide('export','false')" type="button" apes-button (click)="onBtExport()">导出</button>-->
        <button *ngIf="!getButtonHide('export','false')" type="button" apes-button (click)="onBtDownload()" [disabled]="this.isDownloading">下载</button>
        <button *ngIf="!getButtonHide('download','true')" type="button" apes-button (click)="onBtDownload()" [disabled]="this.isDownloading">下载</button>
      </div>
      <ag-grid-angular #grid
                       style="width: 100%;margin-bottom:16px;height:100%;display: inline-table;"
                       class="ag-theme-balham"
                       [domLayout]="domLayout"
                       [rowHeight]="32"
                       [modules]="modules"
                       enableColResize="true"
                       [enableSorting]="enableSorting"
                       [enableFilter]="enableFilter"
                       [localeText]="localeText"
                       [pinnedBottomRowData]="pinnedBottomRowData"
                       [loadingOverlayComponent]="loadingOverlayComponent"
                       [noRowsOverlayComponent]="noRowsOverlayComponent"
                       [frameworkComponents]="frameworkComponents"
                       [rowData]="_rowData"
                       [context]="context"
                       [rowModelType]="rowModelType"
                       [gridOptions]="gridOptions"
                       [columnDefs]="columnDefs"
                       (cellClicked)="onCellClicked($event)"
                       (gridReady)="onGridReady($event)">
      </ag-grid-angular>

      <div class="apes-paging" *ngIf="rowModelType=='clientSide'">
        <apes-pagination [(apesPageIndex)]="pagination.currentPage" [apesTotal]="pagination.total"
                         [apesSize]="'small'"
                         [apesPageSize]="pagination.pageSize"
                         (apesPageIndexChange)="onPageIndexChange()"
                         [apesShowTotal]="totalTemplate"></apes-pagination>
        <ng-template #totalTemplate let-total>
          &nbsp;{{pagination.pageSize * pagination.currentPage - pagination.pageSize + 1}} ~
          {{pagination.pageSize * pagination.currentPage}} - {{pagination.pageSize}}条/页 - 共 {{pagination.total}} 条
        </ng-template>
      </div>
      <div class="apes-paging" *ngIf="rowModelType=='serverSide'">
        已加载{{loadingTotal}}行，总行数{{pagination.total}}
      </div>
    </div>
  `,
  providers: [DrillThroughService],
  host: {},
})

export class FormlyFieldGridDisplay extends ApesField {
  modules: Module[] = AllModules;
  domLayout: any;
  gridApi: any;
  rowSelection: any;
  gridColumnApi: any;
  localeText: any;
  context = {};
  loadingOverlayComponent: any;
  noRowsOverlayComponent: any;
  frameworkComponents;
  columnDefs: any[];
  _rowData: any;
  _domain: any;
  data: any;
  sortedColumnDefs: any[];
  enableFilter = true;
  enableSorting = true;
  rowModelType = 'serverSide';
  buttonList = [];
  pinnedBottomRowData: any[];
  downloadPage = 0;
  isDownloading = false;

  /** 分页器 **/
  loadingTotal = 0;
  pagination = {
    total: 0,
    currentPage: 1,
    lastRow: -1,
    pageSize: 50,
  };
  api: any;
  queryid = '';
  gridOptions: GridOptions;
  sumField: any = [];
  allData: any = [];
  breadcrumbArray: any = [];
  btnRemarks: any = '';
  @ViewChild('grid', {static: false}) grid: any;

  constructor(
    protected gridConfigService: GridConfigService,
    protected events: Events,
    protected expressionService: ExpressionService,
    protected apiService: ApiService,
    protected subject: SubjectService,
    private msg: ApesMessageService,
    private  xlsx: XlsxService,
    private  drillThroughService: DrillThroughService
  ) {
    super(apiService, events, expressionService, subject);
    this.localeText = gridConfigService.getLocaleText();
    this.frameworkComponents = {
      dialogButton: RenderOperatingButtonComponent,
      date: EditorDateComponent,
      loadingOverlay: ApesLoadingOverlayComponent,
      noRowsOverlay: ApesNoRowsOverlayComponent,
      link: ApesRenderLinkComponent,
      upload: RenderUploadComponent,
      renderTooltip: RenderTooltipComponent,
    };
    this.domLayout = 'normal';
    // 初始化 grid
    this.gridOptions = <GridOptions>{
      suppressExcelExport: true,
      suppressCsvExport: true,
      showToolPanel: false,
    };
    this.loadingOverlayComponent = 'loadingOverlay';
    this.noRowsOverlayComponent = 'noRowsOverlay';
  }

  getButtonHide(id: any,show: any ) {
    let iLen = this.buttonList.length;
    let expression = show;
    for (let i = 0; i < iLen; i++) {
      let button = this.buttonList[i];
      if (id == button.id) {
        expression = button.hide ||show;
        break;
      }
    }
    return this.expressionService.eval(expression, {
      context: this.formState,
      model: this.formState.model,
    });
  }

  resetQuery() {
    this.pagination.currentPage = 1;// 每次点击查询按钮时，重置 currentPage
    this.pagination.lastRow = -1;
    this.allData.splice(0, this.allData.length);
    this.sumField.splice(0, this.sumField.length);
  }

  onCellClicked(params) {
    if (!params.colDef.hasOwnProperty('cellEditorParams') || !params.colDef.cellEditorParams.hasOwnProperty('api') || params.rowPinned == 'bottom') return;
    let api = params.colDef.cellEditorParams['api'];
    this.api = api;
    this.breadcrumbArray.push({id: '', name: params.colDef.headerName, api: api, condition: {node: params.data}});
    this.resetQuery();
    this.queryData({node: params.data});
  }

  jump(index, breadcrumb) {
    this.resetQuery();
    this.breadcrumbArray = this.breadcrumbArray.slice(0, index + 1);
    this.api = breadcrumb.api;
    if (breadcrumb.hasOwnProperty('columnDefs')) {
      this.columnDefs = breadcrumb.columnDefs;
      this.setColumns();
    }
    this.queryData(breadcrumb.condition);
  }

  export() {
    this.xlsx.download(this.columnDefs, this.allData);
  }

  ngOnInit() {
    this.context['gridName'] = this.key;
    this.context['grid'] = this;
    this.formState['grid_' + this.key] = this;
    this.context = Object.assign(this.context, this.formState);


    this.buttonList = missingOrEmpty(this.field['buttonList']) ? [] : getO(this.field['buttonList']);
    this.btnRemarks = this.field['btnRemarks'] ? this.field['btnRemarks'] : '';
    if (this.field['domain']) {
      this.field['domain'] = replaceAll(this.field['domain'], '\'', '');
      this._domain = JSON.parse(this.field['domain']);
    }

    if (this.field['rowModelType']) {
      this.enableFilter = true;
      this.enableSorting = true;
      this.rowModelType = 'clientSide';
    } else {
      this.enableFilter = false;
      this.enableSorting = false;
      this.rowModelType = 'serverSide';
      this.gridOptions.cacheBlockSize = 50;
      this.gridOptions.infiniteInitialRowCount = 1;
      this.gridOptions.pagination = false;
      //this.gridOptions.maxBlocksInCache =100;
      this.gridOptions.paginationPageSize = this.pagination.pageSize;
      if (this.field.hasOwnProperty('pages')){
        this.gridOptions.cacheBlockSize = 1000;
        this.gridOptions.paginationPageSize = 1000;
      }
    }
    /**初始化表头**/
    this.columnDefs = [];
    if (this.to.columnDefs) {
      let colDefOperation = {
        headerName: '序号',
        editable: false,
        field: 'operation',
        pinned: 'left',
        width: 40,
        suppressMenu: true,
        cellRenderer: operationCellRenderer,
      };
      this.columnDefs.push(colDefOperation);
      this.to.columnDefs.forEach(element => {
        let colDef = extend(true, {}, element);
        colDef.editable = false;
        colDef.cellClass = 'cell-color';
        this.columnDefs.push(colDef);
      });
    }
    this.sortedColumnDefs = this.createSortedColumnDefs();

    this.setColumns();
    if (this.formState.condition && this.formState.condition.hasOwnProperty('link')) {
      let link = this.formState.condition.link;
      let columns = deepClone(this.columnDefs);
      this.breadcrumbArray.push({
        name: link,
        columnDefs: columns,
        api: this.field['api'],
        condition: this.formState.condition
      });
    }
    let today =   format(new Date(), 'YYYY-MM-DD'); // 2019-01-01 00:
    this.formState['today'] = today;
    this._rowData = this.model[this.key];
  }

  sum(arr, sumField, sumJE: any = {}) {
    sumField.forEach(key => {
      sumJE[key] = 0;
    });
    return arr.reduce((prev: any, curr: any) => {
      sumField.forEach(key => {
        sumJE[key] = prev[key] + curr[key];
      });
      return sumJE;
    }, sumJE);
  }

  getSumField() {
    const sumFieldList = [], fieldObj = {};
    let sumOption = {}, sumFieldStr = '';
    // const columnList = this.gridOptions.columnDefs;
    const columnList = this.columnDefs;
    for (let i = 0, lent = columnList.length; i < lent; i++) {
      const columnObj = columnList[i];
      fieldObj[columnObj['field']] = '';

      if (columnObj['sum'] && toBoolean(columnObj['sum'])) {
        sumFieldList.push(columnObj['field']);
        sumFieldStr += `${columnObj['field']};`;
        sumOption[columnObj['field']] = {scale: columnObj['scale'] ? columnObj['scale'] : 2};
      }
    }
    return {sumFieldList: sumFieldList, fieldObj: fieldObj, sumOption: sumOption, sumFieldStr: sumFieldStr};
  }

  setPinnedBottomRowData(fieldObj, sumFieldList, sumResultList, bRow) {
    if (bRow > 0) {
      for (let i = 0, len = sumFieldList.length; i < len; i++) {
        const fieldKey = sumFieldList[i];
        fieldObj[fieldKey] = sumResultList[0][fieldKey];
      }
    } else {
      fieldObj = [];
    }
    fieldObj['hideBtnBar'] = 'true';

    this.pinnedBottomRowData = [fieldObj];
  }

  setPinnedRowBottom(sumJE: any) {
    let bottomField = {};
    this.gridApi.setPinnedBottomRowData([]);
    this.columnDefs.forEach(item => {
      if (item.sum == 'true' || item.sum == true) {
        let precision = 2;
        if (item.hasOwnProperty('precision')) {
          precision = Number(item.precision);
        }
        bottomField[item.field] = sumJE[item.field].toFixed(precision);
      } else if (item.field == 'operation') {
        bottomField[item.field] = 'sum';
      } else {
        bottomField[item.field] = '';
      }
    });
    this.gridApi.setPinnedBottomRowData([bottomField]);
  }

  ngAfterViewInit() {
    this.grid._nativeElement.style.height = this.to.height || this.field['height'] || '700px';
  }

  extend(data: any) {
    if (data.constructor === Object) {
      for (let item in data) {
        if (data[item] && data[item].length > 0) {
          return data[item];
        }
      }
    } else {
      return data;
    }
  }

  /**
   * 功能：重新设置表头
   * @param ctx
   */
  private setColumns() {
    if (!this.to.columnDefs) return;
    this.columnDefs = [];
    let colDefOperation = {
      headerName: '序号',
      editable: false,
      field: 'operation',
      pinned: 'left',
      suppressMenu: true,
      width: 75,
      cellRenderer: operationCellRenderer,
    };
    this.columnDefs.push(colDefOperation);
    this.to.columnDefs.forEach(element => {
      let colDef = extend(true, {}, element);
      this.columnDefs.push(colDef);

      if (element.buttonList) {
        let buttonList;
        buttonList = replaceAll(element.buttonList, '\'', '"');
        buttonList = replaceAll(buttonList, '`', '\'');
        buttonList = JSON.parse(buttonList);
        buttonList.forEach(btn => {
          let cellButtonListDisabled = btn.disabled || 'false';
          btn.disabled = this.expressionService.eval(cellButtonListDisabled, {
            context: this.formState,
            form: this.form,
            model: this.formState.model,
          });
        });
        colDef.buttonList = buttonList;
      }
      if (colDef.sum == 'true') {
        this.sumField.push(colDef.field);
      }
      if (colDef.hasOwnProperty('changeCellStyle')) {
        let that = this;
        colDef.cellStyle = (params) => {
          let CellStyle = colDef['changeCellStyle'];
          let res = that.expressionService.eval(CellStyle, params);
          return res;
        };
      }

      if (colDef.hasOwnProperty('valueFormatter')) {
        if (colDef.valueFormatter=='currency'){
          colDef.valueFormatter = agCurrency;
        }else if (colDef.valueFormatter=='number'){
          colDef.valueFormatter = agNumber;
          colDef['valueFormatterMeta'] = 'number';
        }
      }
    });
    if (this.gridApi) {
      this.gridApi.setColumnDefs([]);
      this.gridApi.setColumnDefs(this.columnDefs);
      // this.gridApi.sizeColumnsToFit();
    }

  }


  private createSortedColumnDefs() {
    /**字段排序**/
    let columns = extend(true, [], this.to.columnDefs);
    columns.sort((x, y) => {
      if (this.contain(x, y)) {
        return -1;
      } else if (this.contain(y, x)) {
        return 1;
      } else {
        return 0;
      }
    });
    return columns;
  }

  private contain(x: any, y: any) {
    let context = x.context;
    if (missing(context) || missing(y)) return false;
    context = getO(context);
    if (type(context) === 'object') {
      for (let key in context) {
        if (key === y.field) return true;
      }
    }
    return false;
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    if (this.rowModelType == 'clientSide') {
      this.gridApi.hideOverlay();
    }
    let _field: any = this.field;
    if (_field.hasOwnProperty('api')) {
      this.api = _field.api;
      if (_field.hasOwnProperty('queryid')) {
        this.queryid = _field.queryid;
      }
      this.queryData(this.formState.condition);
    }
  }

  /**
   * 功能：自动列宽
   */
  autoSizeAll() {
    let allColumnIds = [];
    this.gridColumnApi.getAllColumns().forEach(column => {
      if (!column.colDef.hasOwnProperty('width')) {
        allColumnIds.push(column.colId);
      }

    });
    this.gridColumnApi.autoSizeColumns(allColumnIds);
  }


  /**
   * 功能：点击分页码时事件
   */
  onPageIndexChange() {
    this.queryData(this.formState.condition);
  }

  /**
   * 功能：查询后台数据
   */
  private queryData(paramCondition) {
    // if (!this.conditionField && this.conditionField.length === 0) return;

    // 检查输入条件
    // const conditionParam = this.getConditionList(this.conditionField);
    // if (!conditionParam.flag) return;  // 必填项未输入
    // if (conditionParam.conditionList.length === 0) {  // 检查什么都不输入的情况下，不让查询
    // return;
    // }

    // if (paramCondition ==undefined) {return};

    // this.setButtonLoadingStatus('action_query', true);
    const sendData = {};
    // sendData['condition'] = conditionParam.conditionList
    const condition = fillField(this._domain, paramCondition, true, '');
    sendData['condition'] = condition;
    sendData["data"] = paramCondition;
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    sendData['queryid'] = this.queryid != '' ? this.queryid : this.api;
    // sendData['customAction'] = this.customAction;
    // sendData['customQuery'] = this.customQuery;
    sendData['customAction'] = false;
    sendData['customQuery'] = false;

    let fieldKey = '_orderField';
    const orderFieldValue = this.model[fieldKey];
    if (orderFieldValue && orderFieldValue.length > 0) {
      sendData['_orderField'] = orderFieldValue[0];
      if (orderFieldValue.length > 1) {
        orderFieldValue.forEach(value => {
          if (sendData['_orderField'] != value) {
            sendData['_orderField'] += ';' + value;
          }
        });
      }
      fieldKey = '_orderType';
      const orderTypeValue = this.model[fieldKey];
      if (orderTypeValue) {
        sendData['_orderType'] = orderTypeValue;
      } else {
        sendData['_orderType'] = 'desc';
      }
    }


    if (this.rowModelType == 'clientSide') {
      this.gridApi.showLoadingOverlay();
      this.apiService.post(this.api, {'body': JSON.stringify(sendData)}).subscribe(
        (body) => {
          if (body) {
            if (body.tableHeader && body.tableHeader.length > 0) {
              this.resetColumnDefs(body.tableHeader);
            }
            this.pagination.total = body.total;
            if (body.size) this.pagination.pageSize = body.size;
            const tempRowData: any[] = body.content;
            this.gridOptions.api.setRowData(tempRowData);
            this._rowData = tempRowData;
            if (body.hasOwnProperty('footer')) {
              // 后端合计字段
              const sumFieldObj = this.getSumField();
              if (sumFieldObj.sumFieldList.length > 0 && body.footer) {
                this.setPinnedBottomRowData(sumFieldObj.fieldObj, sumFieldObj.sumFieldList, body.footer, this._rowData.length);
              }
            } else {
              if (this.sumField.length > 0 && tempRowData.length > 0) {
                let sumJE = {};
                this.sum(tempRowData, this.sumField, sumJE);
                this.setPinnedRowBottom(sumJE);
              }
            }

            if (this._rowData.length === 0) this.msg.info(`未找到满足条件的数据`);


            // 合计字段
            // const sumFieldObj = this.getSumField();
            // if (sumFieldObj.sumFieldList.length > 0) {
            //   this.setPinnedBottomRowData(sumFieldObj.fieldObj, sumFieldObj.sumFieldList, body.footer);
            // }
          }
          // this.setButtonLoadingStatus('action_query', false);
          this.gridApi.hideOverlay();
        }, () => {
          // this.setButtonLoadingStatus('action_query', false);
          this.autoSizeAll();
        });
    } else {
      let dataSource = {
        rowCount: null,
        getRows: (params: any) => this.getRows(params, [], sendData),
      };
      this.gridApi.setServerSideDatasource(null);
      this.gridApi.setServerSideDatasource(dataSource);
    }

  }

  private getRows(params: any, data: any, sendData: any) {
    sendData['size'] = this.pagination.pageSize;
    sendData['page'] = this.pagination.currentPage;
    this.gridApi.showLoadingOverlay();
    // TODO 检查返回值是否不为空数组
    this.apiService.post(this.api, {'body': JSON.stringify(sendData)})
      .subscribe((items) => {
        if (items) {
          if (items.tableHeader && items.tableHeader.length > 0) {
            this.resetColumnDefs(items.tableHeader);
          }

          this.pagination.total = items.total;
          const itemsLength = items.content.length;
          if (itemsLength > 0 && itemsLength >= this.pagination.pageSize) {
            this.pagination.currentPage = this.pagination.currentPage + 1;
          }
          if (itemsLength == 0 || itemsLength < this.pagination.pageSize) {
            this.pagination.lastRow = (this.pagination.currentPage - 1) * this.pagination.pageSize + itemsLength;
          }

          this.allData = this.allData.concat(items.content);

          this.loadingTotal = this.pagination.lastRow !== -1 ? this.pagination.lastRow : params.request.endRow;
          let bHJ = true;
          if (itemsLength > this.pagination.pageSize || !items.hasOwnProperty("pages")) {
            this.pagination.lastRow = itemsLength;
            this.loadingTotal = itemsLength;
            if (this.pagination.currentPage > 2) {
              bHJ = false;
            }
          }

          params.successCallback(items.content, this.pagination.lastRow);
          if (items.hasOwnProperty('footer')) {
            // 后端合计字段
            const sumFieldObj = this.getSumField();
            if (sumFieldObj.sumFieldList.length > 0 && items.footer) {
              this.setPinnedBottomRowData(sumFieldObj.fieldObj, sumFieldObj.sumFieldList, items.footer, this.allData.length);
            }
          } else {
            if (this.sumField.length > 0 && items.content.length > 0 && bHJ) {
              let sumJE = {};
              this.sum(this.allData, this.sumField, sumJE);
              this.setPinnedRowBottom(sumJE);
            }
          }
          if (itemsLength === 0 && this.pagination.lastRow <= 0) this.msg.info(`未找到满足条件的数据`);
        } else {
          params.successCallback([], 0);
        }
        this.gridApi.hideOverlay();
        // this.setButtonLoadingStatus('action_query', false);
      }, () => {
        // this.setButtonLoadingStatus('action_query', false);
      });
  }

  /***
   * 重置表头
   */
  private resetColumnDefs(columnDefs) {
    this.gridApi.setColumnDefs([]);
    this.columnDefs = [{
      headerName: '序号',
      editable: false,
      field: 'operation',
      pinned: 'left',
      width: 75,
      suppressMenu: true,
      cellRenderer: operationCellRenderer,
    }, ...columnDefs];
    // 转换grid-operating-button参数
    this.columnDefs.forEach(element => {
      // let colDef = extend(true, {}, element);
      if (element.buttonList) {
        let buttonList;
        buttonList = replaceAll(element.buttonList, '\'', '"');
        buttonList = replaceAll(buttonList, '`', '\'');
        buttonList = JSON.parse(buttonList);
        buttonList.forEach(btn => {
          let cellButtonListDisabled = btn.disabled || 'false';
          btn.disabled = this.expressionService.eval(cellButtonListDisabled, {
            // context: this.formState,
            form: this.form,
            // model: this.formState.model,
          });
        });
        element.buttonList = buttonList;
      }
    });

    this.columnDefs.forEach((value) => {
      value.enableRowGroup = true;
      value.enablePivot = true;
      value.hide = toBoolean(value.hideExpression);
      if (value.sum == 'true' || value.sum == true) {
        this.sumField.push(value.field);
      }
    });
    this.columnDefs.push({field: 'A', hide: true});
    this.gridApi.setColumnDefs([]);
    this.gridApi.setColumnDefs(this.columnDefs);


  }

  /**
   * 功能：获取表格数据
   * @returns {any[]}
   */
  private getRow(): any[] {
    let rows = [];
    if (this.rowSelection === 'multiple' && this.formState.states === 'submit') {
      //this.gridApi.stopEditing(false);
      this.gridApi.getSelectedNodes().forEach((node) => {
        rows.push(node.data);
      });
    } else {
      this.gridApi.forEachNode((node) => {
        rows.push(node.data);
      });
    }
    return rows;
  }

  getExport() {
    let expression = this.to.import || 'false';
    return this.expressionService.eval(expression, {
      context: this.formState,
      model: this.formState.model,
    });
  }
  getFileName(){
    let filename = this.expressionService.evaluate(this.field['title'], {
      context: this.formState,
      model: this.formState.model,
      value: new Date()
    });
    return  filename;
  }
  /*导出*/
  onBtExport() {
    let data = [];
    let col = [];

    this.columnDefs.forEach((i) => {
      col.push(i);
    });

    data = [col.map(i => i.headerName)];
    this.getRow().forEach(i =>
      data.push(
        col.map(c => {
            let value = deepClone(i[c.field as string]);
            if (value instanceof Object) {
              if (c['exportFormatter']) {
                let expression = c['exportFormatter'];
                value = this.expressionService.evaluate(expression, {
                  value: value,
                });
              } else {
                value = value.name;
              }
              if (value == undefined) {
                value = i[c.field as string].description;
              }
            }
            // 处理序号字段为空的问题
            if (c.field === 'operation') value = data.length;

            return value;
          },
        )),
    );
    let filename = this.getFileName();
    this.xlsx.export({
      sheets: [
        {
          data: data,
          name: 'sheet name',
        },
      ],
      filename: filename? filename + '.xlsx':'export.xlsx'
    });
  }

  /**
   * 下载
   */
  onBtDownload() {
    let downloadData = [];
    let col = [];
    let total = this.pagination.total;
    this.columnDefs.forEach((i) => {
      col.push(i);
    });
    //初始化下载变量
    this.downloadPage = 1;
    if (total > this.getRow().length) {
      this.isDownloading=true;
      this.queryDownloadData(this.formState.condition,downloadData,col)
    } else {
      downloadData = this.getRow();
      this.generateExcl(downloadData, col);
    }

  }

  /**
   * 生成excl
   * @param data
   * @param col
   * @private
   */
  private generateExcl(downloadData, col) {
    let data = [];
    data = [col.map(i => i.headerName)];
    downloadData.forEach(i =>
      data.push(
        col.map(c => {
            let value = deepClone(i[c.field as string]);
            if (value instanceof Object) {
              if (c['exportFormatter']) {
                let expression = c['exportFormatter'];
                value = this.expressionService.evaluate(expression, {
                  value: value,
                });
              } else {
                value = value.name;
              }
              if (value == undefined) {
                value = i[c.field as string].description;
              }
            }
            // 处理序号字段为空的问题
            if (c.field === 'operation') value = data.length;

            return value;
          },
        )),
    );
    let filename = this.getFileName();
    this.xlsx.export({
      sheets: [
        {
          data: data,
          name: 'sheet name',
        },
      ],
      filename: filename? filename + '.xlsx':'export.xlsx'
    });
  }

  /**
   * 功能：查询后台数据(下载)
   */
  private queryDownloadData(paramCondition, data, col) {
    let totalQuantity = 300000; // 下载控制数
    const sendData = {};
    const condition = fillField(this._domain, paramCondition, true, '');
    sendData['condition'] = condition;
    sendData["data"] = paramCondition;
    sendData['size'] = 3000;
    sendData['page'] = this.downloadPage;
    this.apiService.post(this.api, {'body': JSON.stringify(sendData)}).subscribe(
      (body) => {
        if (body) {
          if (body.tableHeader && body.tableHeader.length > 0) {
            this.resetColumnDefs(body.tableHeader);
          }
          if (body.size) this.pagination.pageSize = body.size;
          body.content.forEach((i) => {
            data.push(i);
          })

          if (body.total > totalQuantity) {
            this.msg.info(`数据量过大！目前仅支持30W行以下数据下载`);
            return;
          }
          // || this.downloadPage >= 30
          if (this.pagination.total <= data.length) {
            // if (this.downloadPage >= 30){
            //   this.msg.info(`数据量过大！目前仅支持9W行数据下载`)
            // }
            this.generateExcl(data, col);
            this.isDownloading=false;
          } else {
            this.downloadPage = this.downloadPage + 1;
            this.queryDownloadData(this.formState.condition, data, col)
          }
        }else {
          this.msg.info(`下载接口报错！`)
        }

      }, () => {
        this.autoSizeAll();
      });
  }
}
